package com.itlin.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itlin.bean.Category;
import com.itlin.bean.PageParam;
import com.itlin.common.CustomException;
import com.itlin.dao.CategoryDao;
import com.itlin.service.CategoryService;
import com.itlin.service.DishService;
import com.itlin.service.SetmealService;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 所谓伊人
 * @date 2022/3/24 - 9:34
 */
@Transactional
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryDao dao;
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;

    @Override
    public int add(Category category) {
        return dao.insert(category);
    }

    @Override
    public IPage<Category> findPage(PageParam pageParam) {

        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();

        IPage<Category> page = new Page<>(pageParam.getPage(), pageParam.getPageSize());

        return dao.selectPage(page, qw);
    }

    @Override
    public int delete(long id, int type) {
        if (type == 1) {
            int row = dishService.countByCid(id);

            if (row > 0) {
                throw new CustomException("当前分类下关联了菜品，不能删除");//已经关联套餐，抛出一个业务异常
            }
        } else {
            int row = setmealService.countByCid(id);

            if (row > 0) {
                throw new CustomException("当前分类下关联了套餐，不能删除");
            }
        }
        return dao.deleteById(id);
    }

    @Override
    public int updateById(Category category) {
        return dao.updateById(category);
    }

    @Override
    public List<Category> fingByType(Integer type) {

        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();

        if (type == null) {
            return dao.selectList(null);
        }
        qw.eq(Category::getType, type);

        return dao.selectList(qw);
    }

    @Override
    public Category findById(long id) {
        return dao.selectById(id);
    }


}
